<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */

namespace MoChat\App\Client\Logic\FollowRecord;

use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use MoChat\App\Client\Contract\ClientFollowRecordContract;
use MoChat\App\User\Contract\UserContract;

/**
 * 跟进记录列表.
 *
 */
class IndexLogic
{
    /**
     * @Inject
     * @var ClientFollowRecordContract
     */
    protected $clientFollowRecordService;





    /**
     * 成员列表.
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function handle(array $params): array
    {
        //返回的数据格式
        $where = [];
        $where[] = ['client_id', '=', $params['clientId']];
        $columns = [
            'type',
            'user_id',
            'remark',
            'created_at',
            'followed_at',
            'returned_at',
            'work_contact_id'
        ];
        $options =  ['orderByRaw' => 'created_at desc', 'perPage' => $params['perPage'], 'page' => $params['page'], 'pageName' => 'page'];
        $data = $this->clientFollowRecordService->getClientFollowRecordList($where, $columns, $options);
        //查询跟进人
        foreach ($data['data'] as &$row) {
            $row['followedUserName'] = Db::table('work_employee')->where('id',$row['userId'])->value('name')??"超级管理员";
            $row['name'] = Db::table('work_contact')
                ->where('id',$row['workContactId'])->value('name');
            unset($row['userId']);
        }
        unset($row);
        $data =  my_page($data);
        //统计跟进次数
        $data['count'] = [];
        $res = Db::table('client_follow_record')->where('client_id', $params['clientId'])->selectRaw('count(id) as count,type')->groupBy('type')->get()->toArray();
        foreach ($res as $value) {
            $data['count'][] = $value;
        }
        return $data;
    }
}
